package com.shujia.custom.udtfdemo;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class MyUDTFDemo2 extends GenericUDTF {

    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //a,1,2,3,4,5,6,7,8,9,10,11,12
        //a,0时,1
        //a,2时,2
        //a,4时,3
        //a,6时,4
        //...

        //指定输出的列的个数名字。以及类型
        //创建一个List集合存储列的名字
        ArrayList<String> colNames = new ArrayList<>();
        //创建一个集合存储每一列对象的类型，将每种类型封装成对象
        ArrayList<ObjectInspector> colTypes = new ArrayList<>();
        //将列的名字添加到集合以及列的数据类型添加到集合
        colNames.add("id");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colNames.add("time");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colNames.add("number");
        colTypes.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        //将列名和列的数据类型组合一起
        return ObjectInspectorFactory.getStandardStructObjectInspector(colNames, colTypes);

    }

    @Override
    public void process(Object[] args) throws HiveException {
        //a,1,2,3,4,5,6,7,8,9,10,11,12
        String id = String.valueOf(args[0]);
        int time = 0;
        //从第二列开始遍历
        for (int i = 1; i < args.length; i++) {
            String number = String.valueOf(args[i]);
            String[] strings = {id, time + "时", number};
            forward(strings);
            time += 2;
        }

    }

    @Override
    public void close() throws HiveException {

    }
}
